<template>
  <div class="table-page">
    <GiTable
      title="周转库管理"
      row-key="id"
      :data="dataList"
      :columns="columns"
      :loading="loading"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :pagination="pagination"
      :disabled-tools="['size']"
      :disabled-column-keys="['name']"
      @refresh="search"
    >
      <template #toolbar-left>
        <a-input
          v-model="queryForm.deviceName"
          placeholder="请输入设备名称"
          allow-clear
          @change="search"
        >
          <template #prefix><icon-search /></template>
        </a-input>
        <a-select
          v-model="queryForm.category"
          :options="category_enum"
          placeholder="请选择设备类别"
          allow-clear
          style="width: 150px"
          @change="search"
        />
        <a-input
          v-model="queryForm.modelId"
          placeholder="请输入型号"
          allow-clear
          @change="search"
        >
          <template #prefix><icon-search /></template>
        </a-input>
        <a-input
          v-model="queryForm.factoryId"
          placeholder="请输入出厂编号"
          allow-clear
          @change="search"
        >
          <template #prefix><icon-search /></template>
        </a-input>
        <a-date-picker
          v-model="queryForm.useTime"
          placeholder="请选择使用时间"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          style="height: 32px"
        />
        <a-button @click="reset">
          <template #icon><icon-refresh /></template>
          <template #default>重置</template>
        </a-button>
      </template>
      <template #toolbar-right>
        <a-button
          v-permission="['generator:deviceStore:export']"
          @click="onExport"
        >
          <template #icon><icon-download /></template>
          <template #default>导出</template>
        </a-button>
        <a-button
          v-permission="['generator:deviceStore:export']"
          status="warning"
          @click="onExportExpiring"
        >
          <template #icon><icon-download /></template>
          <template #default>导出即将到期清单</template>
        </a-button>
      </template>

      <!-- 设备类别列插槽 - 使用彩色标签 -->
      <template #category="{ record }">
        <a-tag :color="getCategoryColor((record as DeviceCirculationResp).category)" bordered class="category-tag">
          {{ getCategoryName((record as DeviceCirculationResp).category) }}
        </a-tag>
      </template>

      <!-- 计量单位列插槽 - 使用彩色标签 -->
      <template #measureUnit="{ record }">
        <a-tag :color="getUnitColor((record as DeviceCirculationResp).measureUnit)" bordered>
          {{ getMeasureUnitName((record as DeviceCirculationResp).measureUnit) }}
        </a-tag>
      </template>

      <!-- 状态列插槽 - 改为可点击编辑 -->
      <template #status="{ record }">
        <a-dropdown 
          :trigger="['click']" 
          position="bl"
          @select="(status) => handleStatusChange(record as DeviceCirculationResp, parseInt(status as string))"
        >
          <span class="status-badge" :class="`status-${(record as DeviceCirculationResp).status}`">
            <span class="status-dot"></span>
            {{ getStatusName(typeof (record as DeviceCirculationResp).status === 'number' ? (record as DeviceCirculationResp).status : parseInt(String((record as DeviceCirculationResp).status || '0'))) }}
          </span>
          <template #content>
            <a-doption 
              v-for="statusOption in statusOptions" 
              :key="statusOption.value"
              :value="statusOption.value"
              :class="{ 'selected': (typeof (record as DeviceCirculationResp).status === 'number' ? (record as DeviceCirculationResp).status : parseInt(String((record as DeviceCirculationResp).status || '0'))) === statusOption.value }"
            >
              <span class="status-option">
                <span class="status-dot" :style="{ backgroundColor: getStatusColor(statusOption.value) }"></span>
                {{ statusOption.label }}
              </span>
            </a-doption>
          </template>
        </a-dropdown>
      </template>

      <!-- 校准有效期列插槽 - 添加到期提示 -->
      <template #checkoutDate="{ record }">
        <div v-if="record.checkoutDate" :class="getExpiringClass(record.checkoutDate)">
          <a-tooltip v-if="isExpiringSoon(record.checkoutDate)" :content="getExpiringTooltip(record.checkoutDate)">
            <span style="display: inline-flex; align-items: center; gap: 4px;">
              <icon-exclamation-circle-fill style="color: #f53f3f;" />
              {{ formatDate(record.checkoutDate) }}
            </span>
          </a-tooltip>
          <span v-else>{{ formatDate(record.checkoutDate) }}</span>
        </div>
        <span v-else>--</span>
      </template>
      
      <template #action="{ record }">
        <a-space>
          <a-link
            v-permission="['generator:deviceStore:detail']"
            title="详情"
            @click="onDetail(record as DeviceCirculationResp)"
          >
            详情
          </a-link>
          <a-link
            v-permission="['generator:deviceStore:update']"
            title="使用登记"
            @click="onRegister(record as DeviceCirculationResp)"
          >
            登记
          </a-link>
          <a-link
            v-permission="['generator:deviceStore:detail']"
            title="记录"
            @click="onViewRecords(record as DeviceCirculationResp)"
          >
            记录
          </a-link>
          <a-link
            v-permission="['generator:deviceStore:detail']"
            title="归还"
            @click="onBack(record as DeviceCirculationResp)"
          >
            归还
          </a-link>
          <a-link
            v-permission="['generator:deviceStore:delete']"
            status="danger"
            :disabled="(record as any).disabled"
            :title="(record as any).disabled ? '不可删除' : '删除'"
            @click="onDelete(record as DeviceCirculationResp)"
          >
            删除
          </a-link>
        </a-space>
      </template>
    </GiTable>

    <DeviceCirculationRegisterModal
      ref="DeviceCirculationRegisterModalRef"
      @save-success="handleSaveSuccess"
    />
    <DeviceCirculationDetailDrawer
      ref="DeviceCirculationDetailDrawerRef"
    />
    <DeviceRegisterRecordModal
      ref="DeviceRegisterRecordModalRef"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import DeviceCirculationRegisterModal from './DeviceCirculationRegisterModal.vue'
import DeviceCirculationDetailDrawer from './DeviceCirculationDetailDrawer.vue'
import DeviceRegisterRecordModal from './DeviceRegisterRecordModal.vue'
import { useDownload, useTable } from '@/hooks'
import { isMobile } from '@/utils'
import has from '@/utils/has'
import {
  type DeviceCirculationResp,
  type DeviceCirculationQuery,
  deleteDeviceCirculation,
  exportDeviceCirculation,
  listDeviceCirculation,
  returnDevice,
  updateDeviceStatus,
  exportExpiringDeviceCirculation
} from '@/apis/generator/deviceCirculation'
import type { TableInstanceColumns } from '@/components/GiTable/type'
import { Modal, Message, Notification } from '@arco-design/web-vue'
import dayjs from 'dayjs'

defineOptions({ name: 'DeviceCirculation' })

// 数字映射字典
const categoryMap: Record<number, string> = {
  0: '传感器',
  1: '仪器仪表',
  2: '动态采集系统',
  3: '信息化设备',
  4: '耗材',
  5: '其他设备'
}

const measureUnitMap: Record<number, string> = {
  0: '台',
  1: '支',
  2: '个',
}

const statusMap: Record<number, string> = {
  0: '归还',
  1: '在用',
  2: '外借',
  3: '报废',
}

// 状态选项
const statusOptions = [
  { value: 0, label: '归还' },
  { value: 1, label: '在用' },
  { value: 2, label: '外借' },
  { value: 3, label: '报废' }
]

// 颜色获取方法
const getCategoryColor = (category: number): string => {
  const colors = ['#3498db', '#2ecc71', '#9b59b6', '#e67e22', '#1abc9c', '#34495e']
  return colors[category] || '#95a5a6'
}

const getStatusColor = (status: number): string => {
  const colors = ['#2ecc71', '#3498db', '#f39c12', '#e74c3c']
  return colors[status] || '#95a5a6'
}

const getUnitColor = (unit: number): string => {
  const colors = ['#1abc9c', '#3498db', '#9b59b6']
  return colors[unit] || '#95a5a6'
}

// 字典转换方法
const getCategoryName = (category: number): string => categoryMap[category] || String(category)
const getMeasureUnitName = (unit: number): string => measureUnitMap[unit] || String(unit)
const getStatusName = (status: number): string => statusMap[status] || String(status)

const category_enum = [
  { value: 0, label: '传感器' },
  { value: 1, label: '仪器仪表' },
  { value: 2, label: '动态采集系统' },
  { value: 3, label: '信息化设备' },
  { value: 4, label: '耗材' },
  { value: 5, label: '其他设备' }
]

const queryForm = reactive<DeviceCirculationQuery>({
  deviceName: undefined,
  category: undefined,
  modelId: undefined,
  factoryId: undefined,
  useTime: undefined,
  sort: ['id,desc']
})

const {
  tableData: dataList,
  loading,
  pagination,
  search
} = useTable((page) => 
  listDeviceCirculation({ ...queryForm, ...page }).then(res => {
    // 检查即将到期的设备并提示
    checkExpiringDevices(res.list || [])
    return res
  }), 
  { immediate: true }
)

// 格式化日期
const formatDate = (dateStr?: string | null): string => {
  if (!dateStr) return '--'
  return dayjs(dateStr).format('YYYY-MM-DD')
}

// 判断是否即将到期（距离校准有效期前一个月）
const isExpiringSoon = (checkoutDate?: string | null): boolean => {
  if (!checkoutDate) return false
  const expiryDate = dayjs(checkoutDate)
  const oneMonthLater = dayjs().add(1, 'month')
  const now = dayjs()
  // 如果校准有效期在未来一个月内，且未过期
  return expiryDate.isAfter(now) && expiryDate.isBefore(oneMonthLater) || expiryDate.isSame(oneMonthLater, 'day')
}

// 获取到期提示样式类
const getExpiringClass = (checkoutDate?: string | null): string => {
  if (isExpiringSoon(checkoutDate)) {
    return 'expiring-soon'
  }
  if (checkoutDate && dayjs(checkoutDate).isBefore(dayjs())) {
    return 'expired'
  }
  return ''
}

// 获取到期提示文本
const getExpiringTooltip = (checkoutDate?: string | null): string => {
  if (!checkoutDate) return ''
  const expiryDate = dayjs(checkoutDate)
  const daysLeft = expiryDate.diff(dayjs(), 'day')
  if (daysLeft < 0) {
    return `已过期 ${Math.abs(daysLeft)} 天`
  }
  return `距离校准有效期还有 ${daysLeft} 天`
}

// 检查即将到期的设备并提示
const checkExpiringDevices = (devices: DeviceCirculationResp[]) => {
  const expiringDevices = devices.filter(device => isExpiringSoon(device.checkoutDate))
  if (expiringDevices.length > 0) {
    Notification.warning({
      title: '即将到期设备提醒',
      content: `检测到 ${expiringDevices.length} 个设备即将在30天内到期，请及时处理。`,
      duration: 5000
    })
  }
}

// 导出设备数据
const onExport = () => {
  useDownload(() => exportDeviceCirculation(queryForm))
}

// 导出即将到期设备清单
const onExportExpiring = () => {
  useDownload(() => exportExpiringDeviceCirculation(queryForm))
}

const columns: TableInstanceColumns[] = [
  { title: '设备名称', dataIndex: 'deviceName', slotName: 'deviceName', width: 100 },
  { title: '设备类别', dataIndex: 'categoryDisplay', slotName: 'category', width: 100 },
  { title: '管理编号', dataIndex: 'managementId', slotName: 'managementId', width: 100 },
  { title: '型号', dataIndex: 'modelId', slotName: 'modelId', width: 100 },
  { title: '出厂编号', dataIndex: 'factoryId', slotName: 'factoryId', width: 100 },
  { title: '计量单位', dataIndex: 'measureUnitDisplay', slotName: 'measureUnit', width: 100 },
  { title: '库存数量', dataIndex: 'count', slotName: 'count', width: 100 },
  { 
    title: '状态', 
    dataIndex: 'statusDisplay', 
    slotName: 'status', 
    width: 100,
    tooltip: '点击状态可快速修改'
  },
  { title: '使用时间', dataIndex: 'useTime', slotName: 'useTime', width: 120 },
  { title: '使用人', dataIndex: 'nickname', slotName: 'nickname', width: 120 },
  { title: '使用任务', dataIndex: 'taskName', slotName: 'taskName', width: 120 },
  { title: '归还时间', dataIndex: 'backTime', slotName: 'backTime', width: 100 },
  { title: '备注', dataIndex: 'remark', slotName: 'remark', width: 100 },
  { title: '校准有效期', dataIndex: 'checkoutDate', slotName: 'checkoutDate', width: 120 },
  {
    title: '操作',
    dataIndex: 'action',
    slotName: 'action',
    width: 160,
    align: 'center',
    fixed: !isMobile() ? 'right' : undefined,
    show: has.hasPermOr([
      'generator:deviceStore:detail',
      'generator:deviceStore:update',
      'generator:deviceStore:delete'
    ])
  }
]

/**
 * 处理状态变更
 */
const handleStatusChange = async (record: DeviceCirculationResp, newStatus: number) => {
  const currentStatus = typeof record.status === 'number' ? record.status : parseInt(String(record.status || '0'))
  if (currentStatus === newStatus) {
    return // 状态未改变，直接返回
  }

  const statusName = getStatusName(newStatus)
  const oldStatusName = getStatusName(currentStatus)
  
  Modal.confirm({
    title: '确认修改状态',
    content: `确定要将设备 ${record.deviceName} (编号: ${record.managementId}) 的状态从【${oldStatusName}】修改为【${statusName}】吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        loading.value = true
        const res = await updateDeviceStatus({
          circulationId: record.circulationId,
          status: newStatus
        })
        
        // 检查响应结果
        if (res && res.success === false) {
          const errorMsg = res.data.message || res.msg || '状态修改失败'
          Message.error(errorMsg)
          return
        }
        
        Message.success(res?.data.message || res?.msg || '状态修改成功')
        await search() // 刷新数据
      } catch (error: any) {
        console.error('状态修改失败:', error)
        // 从错误对象中提取错误信息，优先使用 message 字段（后端返回的字段）
        const errorMsg = error?.message || error?.msg || error?.response?.data?.message || error?.response?.data?.msg || '状态修改失败，请重试'
        Message.error(errorMsg)
      } finally {
        loading.value = false
      }
    }
  })
}

const reset = () => {
  queryForm.deviceName = undefined
  queryForm.category = undefined
  queryForm.modelId = undefined
  queryForm.factoryId = undefined
  queryForm.useTime = undefined
  search()
}


/**
 * 处理设备归还
 */
const onBack = (record: DeviceCirculationResp) => {
  Modal.confirm({
    title: '确认回库',
    content: `确定要将设备 ${record.deviceName} (编号: ${record.managementId}) 回库吗？`,
    okText: '确认',
    cancelText: '取消',
    okButtonProps: {
      status: 'danger'
    },
    onOk: async () => {
      try {
        loading.value = true
        const res = await returnDevice(record.circulationId)
        Message.success(res.msg || '回库成功')
        await search()
      } catch (error) {
        console.error('回库失败:', error)
        Message.error('回库失败，请重试')
      } finally {
        loading.value = false
      }
    }
  })
}

/**
 * 处理设备删除
 */
const onDelete = (record: DeviceCirculationResp) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除设备 ${record.deviceName} (编号: ${record.managementId}) 吗？此操作不可恢复。`,
    okText: '确认删除',
    cancelText: '取消',
    okButtonProps: {
      status: 'danger'
    },
    onOk: async () => {
      try {
        loading.value = true
        const res = await deleteDeviceCirculation([record.circulationId])
        Message.success(res.msg || '删除成功')
        await search()
      } catch (error) {
        console.error('删除失败:', error)
        Message.error('删除失败，请重试')
      } finally {
        loading.value = false
      }
    }
  })
}

const DeviceCirculationRegisterModalRef = ref<InstanceType<typeof DeviceCirculationRegisterModal>>()
const DeviceCirculationDetailDrawerRef = ref<InstanceType<typeof DeviceCirculationDetailDrawer>>()
const DeviceRegisterRecordModalRef = ref<InstanceType<typeof DeviceRegisterRecordModal>>()

/**
 * 打开使用登记弹窗
 */
const onRegister = (record: DeviceCirculationResp) => {
  if (record?.circulationId) {
    DeviceCirculationRegisterModalRef.value?.open(record)
  } else {
    console.error('设备记录信息不完整', record)
    Message.error('设备记录信息不完整，请刷新页面后重试')
  }
}

/**
 * 打开设备详情抽屉
 */
const onDetail = (record: DeviceCirculationResp) => {
  DeviceCirculationDetailDrawerRef.value?.open(record.circulationId)
}

/**
 * 处理保存成功回调
 */
const handleSaveSuccess = () => {
  search()
}

/**
 * 查看登记记录
 */
const onViewRecords = (record: DeviceCirculationResp) => {
  if (record?.circulationId) {
    DeviceRegisterRecordModalRef.value?.open(record.circulationId, record.deviceName || '')
  } else {
    console.error('设备记录信息不完整', record)
    Message.error('设备记录信息不完整，请刷新页面后重试')
  }
}
</script>

<style scoped lang="scss">
.table-page .ant-table th,
.table-page .ant-table td {
  padding: 8px;
}

.table-page .ant-table th {
  white-space: normal;
}

.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
  background-color: currentColor;
}

/* 渐变背景色 - 状态标签 */
.status-badge {
  padding: 2px 8px;
  border-radius: 4px;
  color: white;
  font-size: 12px;
  display: inline-flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  }

  &.status-0 {
    background: linear-gradient(135deg, #2ecc71, #27ae60);
  }

  &.status-1 {
    background: linear-gradient(135deg, #3498db, #2980b9);
  }

  &.status-2 {
    background: linear-gradient(135deg, #f39c12, #e67e22);
  }

  &.status-3 {
    background: linear-gradient(135deg, #e74c3c, #c0392b);
  }
}

/* 状态选项样式 */
.status-option {
  display: flex;
  align-items: center;
  padding: 4px 0;
}

/* 选中状态 */
:deep(.arco-dropdown-option.selected) {
  background-color: var(--color-primary-light-1);
}

/* 悬停效果 - 类别标签 */
.category-tag {
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  }
}

/* 表格单元格内边距调整 */
.table-page :deep(.arco-table td) {
  padding: 12px 8px;
}

/* 即将到期样式 */
.expiring-soon {
  color: #f53f3f;
  font-weight: 500;
}

.expired {
  color: #86909c;
  text-decoration: line-through;
}
</style>